package com.jrh.biz.img;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.jrh.common.img.ImageResizer;
import com.jrh.common.util.DateUtils;

/**
 * 图片上传服务
 * 
 * @author jasen.hsu.cn@gmail.com 2012-7-28 下午3:45:56
 */
public class ImgUploadServiceImpl implements ImgUploadService {

    private static final Logger  log             = LoggerFactory.getLogger(ImgUploadServiceImpl.class);

    private String               uploadFilePath;

    private static final String  uploadFloadName = "upload";

    private static final boolean proportion      = true;

    @Override
    public String upload(MultipartFile file, String type) {
        FileOutputStream fs = null;
        InputStream is = null;
        if (file == null || file.isEmpty()) {
            return null;
        }
        try {
            is = file.getInputStream();
            String orgFileName = file.getOriginalFilename();
            int i = orgFileName.lastIndexOf('.');
            String ext = "";
            if (i > 0) {
                ext = orgFileName.substring(i);
            }
            Date now = new Date();
            String filePath = "/" + uploadFloadName + "/" + type + "/"
                              + DateUtils.dateConvert2String(now, DateUtils.DATEPATTERN_YYYY_MM_DD4FILE) + "/";

            String fileName = now.getTime() + "" + ((int) (Math.random() * 10)) + ext;
            
            File f = new File(uploadFilePath + filePath);
            if (!f.exists()) {
                f.mkdirs();
            }
            fs = new FileOutputStream(uploadFilePath + filePath + fileName);
            byte[] buffer = new byte[1024 * 1024];
            int bytesum = 0;
            int byteread = 0;
            while ((byteread = is.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
                fs.flush();
            }
            return filePath + fileName;
        } catch (Exception e) {
            log.error("upload file error:", e);
        } finally {
            try {
                fs.close();
                is.close();
            } catch (Exception e) {
                log.error("close file error:", e);
            }
        }
        return null;
    }

    /**
     * 设置图片大小，等比缩放
     * 
     * @param inputImgFile 原始图片路径，数据库内路径/upload/xxxxx
     * @param outputWidth 宽
     * @param outputHeight 高
     * @return
     */
    public String resize(String inputImgFile, int outputWidth, int outputHeight) {
        if (StringUtils.isBlank(inputImgFile)) {
            return null;
        }
        File orgFile = new File(this.getFullUploadImgPath(inputImgFile));
        if (!orgFile.exists()) {// 原图不存在
            return null;
        }
        String orgFileName = orgFile.getName();
        int i = orgFileName.lastIndexOf('.');
        String ext = "";
        if (i > 0) {
            ext = orgFileName.substring(i);
        }
        String fileName = new Date().getTime() + "" + ((int) (Math.random() * 10)) + ext;
        if (fileName.equals(orgFileName)) {
            fileName = new Date().getTime() + 1 + "" + ((int) (Math.random() * 10)) + ext;
        }
        orgFile.getPath();
        String ouputImgFile = orgFile.getParentFile().getPath();
        boolean success = ImageResizer.resize(this.getFullUploadImgPath(inputImgFile), ouputImgFile + "/" + fileName,
                                              outputWidth, outputHeight, proportion);
        if (success) {
            return inputImgFile.substring(0, inputImgFile.lastIndexOf(orgFileName)) + fileName;
        }
        return null;
    }

    private String getFullUploadImgPath(String inputImgFile) {
        return uploadFilePath + inputImgFile;
    }

    public String getUploadFilePath() {
        return uploadFilePath;
    }

    public void setUploadFilePath(String uploadFilePath) {
        this.uploadFilePath = uploadFilePath;
    }

}
